package com.vcg.community.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import vc.dubbo.result.DubboResult;

import com.vcg.community.dao.UserGroupMapper;
import com.vcg.community.dao.UserMapper;
import com.vcg.community.dao.UsergrouprelationMapper;
import com.vcg.community.model.User;
import com.vcg.community.model.UserGroup;
import com.vcg.community.model.Usergrouprelation;
import com.vcg.community.model.Userrelation;

public class GroupGetServiceImpl implements GroupGetService {

	@Autowired
	private UserGroupMapper userGroupDao;
	@Autowired
	private UserMapper userDao;
	@Autowired
	private UsergrouprelationMapper usrGroupRelationDao;
	@Autowired
	DataSourceTransactionManager txManager;

	public DubboResult<List<UserGroup>> getUserGroups(Integer userId) {
		DubboResult<List<UserGroup>> resultObject=new DubboResult<List<UserGroup>>(0,null);
		try{
			List<UserGroup> lstGroup=userGroupDao.getUserGroup(userId);
			resultObject.setResult(lstGroup);			
		}catch(Exception ex){
			resultObject.setCode(-1);
			resultObject.setCodeError(ex.toString());			
		}
		return resultObject;
	}
	
	public DubboResult<List<User>> getGroupUsers(Integer groupId){
		DubboResult<List<User>> resultObject=new DubboResult<List<User>>(0,null);
		try{
			List<User> lstUser=userDao.getGroupUsers(groupId);
			resultObject.setResult(lstUser);
		}catch(Exception ex){
			resultObject.setCode(-1);
			resultObject.setCodeError(ex.toString());
			
		}
		return resultObject;
	}

	public DubboResult joinGroup(Integer userId, Integer groupId) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

		TransactionStatus status = txManager.getTransaction(def);

		DubboResult resultObject=new DubboResult(0,"",null);
		try{
			Usergrouprelation ugr=new Usergrouprelation();
			ugr.setUserId(userId);
			ugr.setGroupId(groupId);
			usrGroupRelationDao.insert(ugr);
		}catch(Exception ex){
			txManager.rollback(status);
			resultObject.setCode(-1);
			resultObject.setCodeError(ex.toString());			
			return resultObject;
		}
		txManager.commit(status);
		return resultObject;		
	}

}
